package com.hugh.lagoucloudgateway9002.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.atomic.LongAdder;

/**
 * @Author: Hugh
 * @Date: 2020/7/24
 */
@Component
public class IpLimitUtil {

    @Autowired
    private MapCacheUtil cacheUtil;

    public Boolean isLimited(String ip, long periodInMillis, Integer limitCount){

        Object o = cacheUtil.get(ip);
        if(Objects.isNull(o)){
            LongAdder count = new LongAdder();
            count.increment();
            cacheUtil.add(ip, count, periodInMillis);
            return Boolean.FALSE;
        }
        LongAdder count = (LongAdder)o;
        count.increment();
        if(count.intValue() > limitCount){
            return Boolean.TRUE;
        }else {
            cacheUtil.add(ip, count, periodInMillis);
            return Boolean.FALSE;
        }
    }
}
